package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 通过httpclient ，改造登录凭证校验请求
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        final String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        // log.info("登录获取的返回数据：res={}", res);
        // 解析校验结果,获取openId
        //     解析json数据到对象中
        final JSONObject jsonObject = JSON.parseObject(res);
        final String openid = (String) jsonObject.get("openid");
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        // 判断是否为新用户,查询user表中的openid
        User user = userMapper.select(openid);
        if (user == null) {// 如果是新用户,就新增
            user = User.builder()
                    .openid(openid)
                    .name("你坤哥不能给你定名字，要你自己写奥")
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 如果不是新用户,直接返回登录结果,直接返回
        return user;
    }
}
